/********************************************************************************
  * @file    comboboxitemdelegate.cpp
  * @author  Lun Li
  * @version V2.2.0
  * @date    2022.7.8
  * @brief   This file provides all ComboBoxItemDelegate functions.
  *******************************************************************************/

#include "comboboxitemdelegate.h"

ComboBoxItemDelegate::ComboBoxItemDelegate(const QStringList &strList, QObject *parent)
    : QStyledItemDelegate(parent),
      m_strList(strList)
{

}

QWidget *ComboBoxItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);

    // 编辑单元格时弹出QComboBox
    QComboBox *comboBox = new QComboBox(parent);
    comboBox->setEditable(false);
    for (const QString &str : m_strList) {
        comboBox->addItem(str);
    }
    return comboBox;
}

void ComboBoxItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    // 单元格有数据时，弹出QComboBox时转到该数据对应的index
    QString text = index.model()->data(index, Qt::EditRole).toString();
    QComboBox *comboBox = static_cast<QComboBox *>(editor);
    int boxIndex = comboBox->findText(text);
    comboBox->setCurrentIndex(boxIndex);
}

void ComboBoxItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    // 编辑单元格数据时，将用户选定的数据保存到model中
    QComboBox *comboBox = static_cast<QComboBox *>(editor);
    QString text = comboBox->currentText();
    model->setData(index, text, Qt::EditRole);
}
